﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web.UI;
using BLL;
using Model;
using System.Configuration;
using System.Web.Security;

public partial class ProductAging_ManuAging_AgingBoxwithNoRefresh : System.Web.UI.Page
{
    private static readonly string Server_IP = ConfigurationManager.AppSettings["Server_IP"];

    private Aging ag;
    private AgingInfo agi;
    private static string Deviceno;
    //private static string agingID;
    //private static TimeSpan datediff;
    private IList<string> AgingIDs;
    private static string IDs = Deviceno + "ids";

    private string agingID 
    {
        get { return ViewState["agingID"].ToString(); }
        set { ViewState["agingID"] = value; }
    }

    private TimeSpan datediff
    {
        get { return (TimeSpan)ViewState["datediff"]; }
        set { ViewState["datediff"] = value; }
    }

    public ProductAging_ManuAging_AgingBoxwithNoRefresh()
    {
        ag = new Aging();
        agi = new AgingInfo();
        AgingIDs = null;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        GetData();        
        DisableButtonforQE();
    }

    /// <summary>
    /// 质量查看时效看板权限　
    /// </summary>
    protected void DisableButtonforQE()
    {
        if (!Roles.IsUserInRole(User.Identity.Name, "Aginger") && Roles.IsUserInRole(User.Identity.Name, "Quality Engineer"))
        {
            this.Button1.Enabled = false;
            this.Button4.Enabled = false;
            this.Button2.Enabled = false;
        }
    }

    /// <summary>
    /// 时效看板中，客户端倒计时完成后，需要启动定时器，定时刷新数据
    /// </summary>
    protected void RefreshAfterOperation()
    {
        //DisableButtonforQE();
        this.Timer1.Enabled = true;
    }

    private void GetData()
    {
        Deviceno = Request.QueryString["deviceno"].ToString();
        this.Label1.Text = Deviceno;
        //Set_agi();
        agi = ag.GetbyDeviceName(Deviceno);
        if (string.IsNullOrEmpty(agi.AgingID))
        {
            this.Timer1.Enabled = true;
        }
        else
        {
            this.Timer1.Enabled = false;
            this.Label2.ForeColor = Color.Blue;
            agingID = agi.AgingID;
            //Set_AgingIDs();
            AgingIDs = ag.GetIDsbyDeviceName(Deviceno, agi.InBoxManuTime);
            this.LinkButton1.Enabled = true;
            string url = Server_IP + "/pa/ProductAging/ViewAging/AgingDetailforBoard.aspx?agingID=" + agingID;
            this.LinkButton1.Attributes.Add("onclick", "javascript:return window.open('http://" + url + "','AgingDetail','height=600,width=900,top=100,left=250,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no')");

            if (string.IsNullOrEmpty(agi.TempStartManuUser))
            {
                datediff = agi.InBoxManuTime.AddMinutes(30).Subtract(DateTime.Now);
                if (datediff.TotalSeconds > 0)
                {
                    //升温倒计时
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(),
                        "TimeCountDown", "<script>var t = " + (int)datediff.TotalSeconds + "; fun1();</script>", false);
                }
                else
                {
                    //恒温开始提示
                    this.Label2.Text = "00:00";
                    this.Button1.Enabled = true;
                    this.Button1.BackColor = Color.Red;

                    RefreshAfterOperation();
                }
            }
            else          //恒温开始已确认，恒温结束未确认
            {
                datediff = agi.TempStartManuTime.AddHours((double)agi.TimeSpec).Subtract(DateTime.Now);
                if (datediff.TotalSeconds > 0)
                {
                    //恒温倒计时
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(),
                        "TimeCountDown2", "<script>var t = " + (int)datediff.TotalSeconds + "; fun3();</script>", false);
                    if (string.IsNullOrEmpty(agi.PatrolManuUser))
                    {
                        this.Button4.Enabled = true;

                        RefreshAfterOperation();
                    }
                }
                else
                {
                    //恒温结束提示
                    this.Label2.Text = "00:00:00";
                    this.Button2.Enabled = true;
                    this.Button2.BackColor = Color.Red;

                    RefreshAfterOperation();
                }
            }
        }
    }

    private void Set_agi()
    {
        if (Cache[Deviceno] == null)
        {
            agi = ag.GetbyDeviceName(Deviceno);
            if (!string.IsNullOrEmpty(agi.AgingID))
            {
                //设置缓存10分钟的弹性有效期
                Cache.Insert(Deviceno, agi, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 1, 0));
            }
        }
        else
        {
            agi = (AgingInfo)Cache[Deviceno];
        }
    }

    private void Set_AgingIDs()
    {
        if (Cache[IDs] == null)
        {
            AgingIDs = ag.GetIDsbyDeviceName(Deviceno, agi.InBoxManuTime);
            Cache.Insert(IDs, AgingIDs, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 1, 0));
        }
        else
        {
            AgingIDs = (IList<string>)Cache[IDs];
        }
    }

    private void RemoveCache()
    {
        //if (Cache[Deviceno] != null)
        //{
            Cache.Remove(Deviceno);
        //}
    }

    /// <summary>
    /// 恒温开始确认
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        //RemoveCache();
        //在这里先查出此时效箱中的所有批次，再逐个确认
        string str = "";
        foreach (string str1 in AgingIDs)
        {
            str = ag.Aging_TempStartManu(str1, User.Identity.Name);
        }
        ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');location.reload();</script>", false);
        
        //Response.Redirect(Request.Url.ToString());

        //this.Button1.Enabled = false;
        //this.Button1.BackColor = Color.Empty;
        //GetData();
    }

    /// <summary>
    /// 恒温结束确认
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button2_Click(object sender, EventArgs e)
    {
        //RemoveCache();
        //if (Cache[IDs] != null)
        //{
        //    Cache.Remove(IDs);
        //}
        if (Isvalid_TempEnd())
        {
            string str = "";
            foreach (string str1 in AgingIDs)
            {
                str = ag.Aging_TempEndManu(str1, User.Identity.Name);
            }
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');location.reload();</script>", false);
        };
        //Response.Redirect(Request.Url.ToString()); 

        //this.Button4.Enabled = false;
        //this.Button4.BackColor = Color.Empty;
        //GetData();  
    }

    /// <summary>
    /// 生产巡查确认
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button4_Click(object sender, EventArgs e)
    {
        //RemoveCache();
        string str = "";
        foreach (string str1 in AgingIDs)
        {
            str = ag.Aging_PatrolManu(str1, User.Identity.Name);
        }
        ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');location.reload();</script>", false);
        
        //Response.Redirect(Request.Url.ToString());
    }

    /// <summary>
    /// 定时间隔60秒
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        //Response.Redirect(Request.Url.ToString());
        GetData();
    }

    /// <summary>
    /// 所有会刷新页面的操作之后，都重新加载下页面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>location.reload();</script>", false);        
    }

    /// <summary>
    /// 恒温结束按钮按下时，做服务器端的验证（看BUG是否从这里入口的）
    /// </summary>
    protected bool Isvalid_TempEnd()
    {
        foreach (string str1 in AgingIDs)
        {
            string message;
            if (!ag.Isvalid_TempEnd(str1, out message))
            {
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + message + "');location.reload();</script>", false);
                return false;
            }
        }
        return true;
    }
}
